import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_shopcar_test/database/method_dao.dart';
import 'package:flutter_shopcar_test/database/sqlite_data.dart';
import 'package:flutter_shopcar_test/model/index.dart';
import 'package:flutter_shopcar_test/router.dart';
import 'package:get/get.dart';

class HomePageLogic extends GetxController {

  List<GoodsListModel> goodsList = [];

  @override
  void onInit() async {
    super.onInit();
    getData();
  }

  void getData() async {
    goodsList = await MethodDao.queryGoodsList();
    print("HomePageLogic--:${goodsList.length}");
    if(goodsList.isEmpty){
      await SqliteDataManger.getInstance().initData();
      goodsList = await MethodDao.queryGoodsList();
    }
    update();
  }

  void goToOrder() {
    Get.toNamed(RouterName.orderPage);
  }

  void queryGoodsList() async {
    goodsList = await MethodDao.queryGoodsList();
    update();
  }

  void addCount(GoodsListModel model) {
    if(model.goodsQty != null) {
      model.goodsQty = model.goodsQty! + 1;
    }
    update();
  }

  void subCount(GoodsListModel model) async {
    if(model.goodsQty != null) {
      if(model.goodsQty! < 1) {
        return ;
      }
      model.goodsQty = model.goodsQty! - 1;
      if(model.goodsQty! == 0) {
        List<CartModel> cartGoodsList = await MethodDao.queryCartGoodsList();
        CartModel? data = cartGoodsList.firstWhereOrNull((item) => item.shopCartCode == model.goodsCode);
        if(data != null) {
          await MethodDao.deleteCartGoodsList(data);
        }
      }
      update();
    }
  }

  num totalPrice() {
    num total = 0;
    if(goodsList.isNotEmpty) {
      for (var e in goodsList) {
        if(e.goodsQty != null && e.goodsQty! > 0) {
          total = total + (e.goodsQty! * (e.goodsPrice ?? 0));
        }
      }
    }
    return total;
  }

  void addCart() async {
    if(goodsList.isEmpty) {
      showDialog(title: '暂无商品');
      return ;
    }
    bool flag = goodsList.every((e) => e.goodsQty == 0);
    if(flag) {
      showDialog(title: '请选择商品');
      return ;
    }
    List<CartModel> cartGoodsList = await MethodDao.queryCartGoodsList();
    List<CartModel> cartList = [];

    for (var e in goodsList) {
      if(e.goodsQty != null && e.goodsQty! > 0) {
        CartModel m = CartModel();
        m.id = e.id;
        m.shopCartName = e.goodsName;
        m.shopCartCode = e.goodsCode;
        m.shopCartPrice = e.goodsPrice;
        m.shopCartQty = e.goodsQty;
        cartList.add(m);
      }
    }
    if(cartList.isNotEmpty) {
      for (var e in cartList) {
        CartModel? model = cartGoodsList.firstWhereOrNull((item) => item.shopCartCode == e.shopCartCode);
        if(model != null) {
          if(e.shopCartQty != model.shopCartQty) {
            await MethodDao.updateCartGoodsList(e);
          }
        } else {
          await MethodDao.insertCartGoodsList(e);
        }
      }
    }
    updateGoods();
    Get.toNamed(RouterName.shopCartPage)?.then((e) {
      queryGoodsList();
    });
  }

  void updateGoods() async {
    if(goodsList.isNotEmpty) {
      for (var e in goodsList) {
        await MethodDao.updateGoodsList(e);
      }
    }
  }

  void showDialog({required String title}) {
    showCupertinoDialog(
        context: Get.context!,
        builder: (context) {
          return CupertinoAlertDialog(
            title: const Text(
              '提示',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
            content: Padding(
              padding: const EdgeInsets.only(top: 6),
              child: Text(title, style: const TextStyle(fontSize: 15), textAlign: TextAlign.center,),
              ),
            actions: [
              CupertinoDialogAction(
                  onPressed: () {
                    Get.back();
                  },
                  child: const Text('确定')),
              CupertinoDialogAction(
                  onPressed: () {
                    Get.back();
                  },
                  child: const Text('取消')),
            ],
          );
        });

  }

}
